package com.wenbai.servicelightluxurystickers.controller;

import com.wenbai.servicelightluxurystickers.common.RedisConstants;
import com.wenbai.servicelightluxurystickers.entity.StickPost;
import com.wenbai.servicelightluxurystickers.mapper.StickPostMapper;
import com.wenbai.servicelightluxurystickers.service.StickPostService;
import com.wenbai.servicelightluxurystickers.utils.RedisUtil;
import com.wenbai.servicelightluxurystickers.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/stick/post")
public class StickPostController {
    @Autowired
    private StickPostService stickPostService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private StickPostMapper stickPostMapper;

    @GetMapping("/select")
    public Response<List<StickPost>> select() {
        return Response.success(stickPostService.selectPost(), "查询成功");
    }

    @GetMapping("/postViewIncr")
    public Response<String> postView(int postId) {
        // 增加浏览量
        String key = RedisConstants.POST_VIEW_COUNT_KEY + postId;
        boolean hasKey = redisUtil.hasKey(key);
        if (Boolean.FALSE.equals(hasKey)) {
            // 数据库获取当前浏览量
            StickPost stickPost = stickPostMapper.selectById(postId);
//            redisUtil.set(key, stickPost.getViewCount());
            stringRedisTemplate.opsForValue().set(key, stickPost.getViewCount().toString());
        }
        redisUtil.incr(key);
        redisUtil.expire(key,24);
        return Response.success("浏览量+1");
    }

    @GetMapping("/forumUserSelect")
    public Response<List<StickPost>> forumUserSelect(int postId) {
        return Response.success(stickPostService.selectForumUser(postId),"查询成功");
    }

    @GetMapping("/postByUserId")
    public Response<List<StickPost>> postByUserId(int userId) {
        return Response.success(stickPostService.selectPostByUserId(userId),"查询成功");
    }
}
